
Imports System
Imports System.Web.UI
Imports System.IO
Imports System.Collections
Imports System.Text
Imports System.Xml
Imports System.Web

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for BaseWebPage.
	''' </summary>
	Public Class BaseWebPage
		Inherits System.Web.UI.Page
		Public pageTemplate As MainLayout
		Public TemplateID As Integer = -1
		Public cssFileName As String = "2bMates"
		Public bFriendsListPage As Boolean = False
		Public sSkyscraperAdvertisementCode As String = Constants.SKYSCR_ADV_CODE

		' Auto login from an external link
		Public Function AutoLogin(ByVal request As System.Web.HttpRequest) As Boolean
			Dim autoLoggedIn As Boolean = False

			Dim loginEmail As String = Request(Constants.LOGIN_PARAM_USER)
			Dim loginKey As String = Request(Constants.LOGIN_PARAM_KEY)

			If loginEmail <> Nothing AndAlso loginKey <> Nothing Then
				Dim usr As BO.User = BO.Users.LoginWithPassHash(loginEmail, loginKey)
				LoggedUser = usr
				autoLoggedIn = (usr <> Nothing)
			End If

			Return autoLoggedIn
		End Function

		Public Property LoggedUser() As BO.User
			Get
				' Retrieve the logged-in user, by it's ID, stored in the sesion object
					'Common.Utils.GetLoggedUser( Session );
				Return GetLoggedUser()
			End Get

			Set
				If value = Nothing Then
					' Logout
					Session(Constants.ssnUserID) = Nothing
					Session.Abandon()
				Else
					' Login
					Session(Constants.ssnUserID) = value.ID

					' Add the session state to the global cache
					'
					' NOTE: only if the user allows viewing his
					' online status.
					'
					' Changing this setting of the user would take
					' effect next time he logs-in
					'
					If value.ShowOnline Then
						Constants.SESSIONS(Session.SessionID) = Session
						Constants.LOGGED_USERS_IDS(value.ID) = value
					End If

					' Init search filter used when users are not logged to null
					Session(Constants.ssnSearch_ViewDetailsNotLogged) = Nothing
				End If
			End Set
		End Property

		Public Function InitStrLogOut() As String
			If Me.LoggedUser = Nothing Then

				Return "&nbsp;"
			Else
				Return "<a href='" + Constants.LOGOUT + "?logout=1'><b>Log out</b></a>"
			End If
		End Function
		Public Shared Function InitTopMenu() As String
			Dim musicID As String = "-1"
			Dim music As BO.SpecialPage = BO.SpecialPages.GetSpecialPageByName(Constants.MUSIC_PAGE)
			If music <> Nothing Then
				musicID = music.ID.ToString()
			End If
			Return Constants.STANDARD_TOP_MENU.Replace("[music_id]", musicID)
		End Function
		Public Function InitStyle(ByVal styleName As String) As String
			If styleName <> "" Then
				Return "<link rel='stylesheet' href='" + styleName + "' type='text/css'>"
			End If
			Return ""
		End Function

		Public Function InitWAVFileURL(ByVal url As String) As String
			If url <> Nothing AndAlso url <> "" Then
				Return "<EMBED src='" + url + "' autostart=true loop=true volume=100 hidden=true><NOEMBED><BGSOUND src='" + url + "'></NOEMBED>"
			End If
			Return ""
		End Function

		Public Function InitBGImage(ByVal url As String) As String
			If url <> Nothing AndAlso url <> "" Then
				Return "background='" + url + "'"
			End If
			Return ""
		End Function

		Public Function constructMusicURL(ByVal url As String) As String
			Return "javascript: popWin('" + Constants.PLAY_MUSIC + "?filename=" + url + "')"
		End Function

		Public Function constructImageURL(ByVal url As String) As String
			Return "javascript: popWinImage('" + Constants.SEE_IMAGE + "?filename=" + url + "')"
		End Function

		Public Sub InitSessionSearchVars()
			' init session search variables
			Session(Constants.ssnSearchFilter) = Nothing
			Session(Constants.ssnSearchCriteria) = Nothing
			'Session[Constants.ssnViewDetails] = null;
		End Sub
		Protected Overloads Overrides Sub AddParsedSubObject(ByVal Control As Object)
			If pageTemplate = Nothing Then
				LoadTemplate()
			End If
			pageTemplate.AddCenterControl(DirectCast(Control, System.Web.UI.Control))
		End Sub

		Protected Sub LoadTemplate()
			Dim template As String = "Controls/MainLayout.ascx"
			pageTemplate = DirectCast(Page.LoadControl(template), MainLayout)
			pageTemplate.StrLogOut = InitStrLogOut()
			pageTemplate.StrTopMenu = InitTopMenu()
			pageTemplate.PageTitle = Constants.DEFAULT_PAGE_TITLE

			Dim regParam As String = Request.Params(Constants.REGISTRATION_PARAM)
			Dim groupParam As String = Request.Params(Constants.GROUP_PARAM)
			Constants.CATEGORIES = New BO.Categories()

			'			if( regParam != null && regParam != "" && Convert.ToInt32(regParam) == Constants.REGISTRATION_VALUE && groupParam == null )
			'			{
			'				pageTemplate.litLogOut.Visible = false;
			'				pageTemplate.litTopMenu.Visible = false;
			'			}

			MyBase.Controls.Add(pageTemplate)
		End Sub
		Public Sub btnLogOut_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			LoggedUser = Nothing
		End Sub
		Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
			Dim stringBuilder As New StringBuilder()
			Dim stringWriter As New StringWriter(stringBuilder)
			Dim htmlWriter As New HtmlTextWriter(stringWriter)
			MyBase.Render(htmlWriter)
			Dim html As String = stringBuilder.ToString()
			Dim start As Integer = html.IndexOf("<form name=""") + 12
			Dim [end] As Integer = html.IndexOf("""", start)
			Dim formID As String = html.Substring(start, [end] - start)
			Dim replace As String = formID.Replace(":", "_")
			html = html.Replace("document." + formID, "document." + replace)
			writer.Write(html)
		End Sub

		Public Function initBlogMessage(ByVal msg As String) As String
			' init Message
			Dim body As String = ""
			Dim link As String = ""
			Dim temp As String = ""
			Dim nStartIndex As Integer = -1
			Dim nEndIndex As Integer = -1
			Dim isEnd As Boolean = False
			temp = msg
			' init Links		
			While temp.IndexOf(Constants.BLOG_ADD_LINK_TAG) <> -1
				' init start index of the link
				nStartIndex = temp.IndexOf(Constants.BLOG_ADD_LINK_TAG)
				' init end index of the link
				nEndIndex = temp.Substring(nStartIndex, temp.Length - nStartIndex).IndexOfAny(New Char() {" "C, Chr(13), Chr(10)})

				If nEndIndex = -1 Then
					nEndIndex = temp.Length - 1
					isEnd = True
				Else
					nEndIndex += nStartIndex
				End If

				' extract the link
				If isEnd Then
					link = temp.Substring(nStartIndex + Constants.BLOG_ADD_LINK_TAG.Length, nEndIndex - nStartIndex - Constants.BLOG_ADD_LINK_TAG.Length + 1)
				Else
					link = temp.Substring(nStartIndex + Constants.BLOG_ADD_LINK_TAG.Length, nEndIndex - nStartIndex - Constants.BLOG_ADD_LINK_TAG.Length)
				End If

				' construct body message
				body += temp.Substring(0, nStartIndex)
				body += "<a href=" + link

				If Not link.ToLower().StartsWith(Constants.APPLICATION_URL.ToLower()) Then
					body += " target='_blank'"
				End If

				body += ">" + link + "</a>"
				' get message body after the extracted link
				If isEnd Then
					temp = temp.Substring(nEndIndex + 1)
				Else
					temp = temp.Substring(nEndIndex)
				End If
			End While
			body += temp

			nStartIndex = -1
			nEndIndex = -1
			isEnd = False
			temp = body
			body = ""

			' init images
			While temp.IndexOf(Constants.BLOG_ADD_IMAGE_TAG) <> -1
				' init start index of the link
				nStartIndex = temp.IndexOf(Constants.BLOG_ADD_IMAGE_TAG)
				' init end index of the link
				nEndIndex = temp.Substring(nStartIndex, temp.Length - nStartIndex).IndexOfAny(New Char() {" "C, Chr(13), Chr(10)})

				If nEndIndex = -1 Then
					nEndIndex = temp.Length - 1
					isEnd = True
				Else
					nEndIndex += nStartIndex
				End If

				' extract the link
				If isEnd Then
					link = temp.Substring(nStartIndex + Constants.BLOG_ADD_IMAGE_TAG.Length, nEndIndex - nStartIndex - Constants.BLOG_ADD_IMAGE_TAG.Length + 1)
				Else
					link = temp.Substring(nStartIndex + Constants.BLOG_ADD_IMAGE_TAG.Length, nEndIndex - nStartIndex - Constants.BLOG_ADD_IMAGE_TAG.Length)
				End If

				' construct body message
				body += temp.Substring(0, nStartIndex)
				body += "<br><img name='blogImage' src=" + link
				body += "><br>"
				' get message body after the extracted link
				If isEnd Then
					temp = temp.Substring(nEndIndex + 1)
				Else
					temp = temp.Substring(nEndIndex)
				End If
			End While
			body += temp

			Return body
		End Function

		Public Function getBeginning(ByVal text As String, ByVal length As Integer) As String
			If text.Length > length Then
				Return (text.Substring(0, length) + "...")
			End If
			Return text
		End Function

		Public Function showLinksInMessage(ByVal msg As String, ByVal bCutLinks As Boolean) As String
			Dim body As String = ""
			Dim link As String = ""
			Dim temp As String = ""
			Dim linkStartIndex As Integer = -1
			Dim linkEndIndex As Integer = -1
			temp = msg
			Dim isEnd As Boolean = False

			'ivan change - if it's html the do not transform
			If temp.IndexOf("<") <> -1 AndAlso temp.IndexOf(">") <> -1 Then
				Return msg
			End If

			' ivan change - leaved commented please
'			 temp = temp.Replace("<a href=http://", "<a href=h$$p://");
'			temp = temp.Replace("<a href=\"http://", "<a href=\"h$$p://");
'			temp = temp.Replace("<a href='http://", "<a href='h$$p://");
'
'			temp = temp.Replace("src=http://", "src=h$$p://");
'			temp = temp.Replace("src=\"http://", "src=\"h$$p://");
'			temp = temp.Replace("src='http://", "src='h$$p://");
'			


			While temp.IndexOf("http://") <> -1
				' init start index of the link
				linkStartIndex = temp.IndexOf("http://")
				' init end index of the link
				linkEndIndex = temp.Substring(linkStartIndex, temp.Length - linkStartIndex).IndexOfAny(New Char() {" "C, Chr(13), Chr(10)})
				'if(linkEndIndex == -1)
				'	linkEndIndex = temp.Substring(linkStartIndex, temp.Length - linkStartIndex).IndexOf("\r");	
				'if(linkEndIndex == -1)
				'	linkEndIndex = temp.Substring(linkStartIndex, temp.Length - linkStartIndex).IndexOf("\n");
				If linkEndIndex = -1 Then
					linkEndIndex = temp.Length - 1
					isEnd = True
				Else
					linkEndIndex += linkStartIndex
				End If

				' extract the link
				If isEnd Then
					link = temp.Substring(linkStartIndex, linkEndIndex - linkStartIndex + 1)
				Else
					link = temp.Substring(linkStartIndex, linkEndIndex - linkStartIndex)
				End If

				' construct body message
				body += temp.Substring(0, linkStartIndex)
				body += "<a href=" + link

				If Not link.ToLower().StartsWith(Constants.APPLICATION_URL.ToLower()) Then
					body += " target='_blank'"
				End If

				body += ">" + getLinkCut(link, bCutLinks) + "</a>"
				' get message body after the extracted link
				If isEnd Then
					temp = temp.Substring(linkEndIndex + 1)
				Else
					temp = temp.Substring(linkEndIndex)
				End If
			End While
			body += temp
			msg = body

			' ivan change - leaved commented please
'			msg = msg.Replace("h$$p://", "http://");
'			


			Return msg
		End Function

		Private Function getLinkCut(ByVal link As String, ByVal bCutLinks As Boolean) As String
			If bCutLinks Then
				If link.Length > Constants.MAX_LINK_LENGTH Then
					link = link.Substring(0, Constants.MAX_LINK_LENGTH) + "..."
				End If
			End If
			Return link
		End Function

		Protected Function removeScriptTags(ByVal str As String) As String
			Dim i As Integer = 0
			Dim tagsCount As Integer = Constants.arrScriptToBeDeleted.Length

			i = 0
			While i < tagsCount
				str = str.Replace(Constants.arrScriptToBeDeleted(i), "..")
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
			Return str
		End Function

		Protected Function isHTML(ByVal sStringValue As String) As Boolean
			If sStringValue.IndexOf("<") <> -1 Then
				Return True
			Else
				Return False
			End If
		End Function

		Public Sub initPageTitles(ByVal pageASPXFilename As String, ByVal xmlFileName As String, ByVal pageForm As System.Web.UI.HtmlControls.HtmlForm, ByVal page As System.Web.UI.Page, ByVal htPageConstants As Hashtable)
			Dim doc As New XmlDocument()
			Dim pageRoot As XmlNodeList = Nothing
			Dim curNode As XmlNode, curPageNode As XmlNode
			Dim i As Integer

			' TODO : validate xml
			If xmlFileName = "" Then
				doc.Load(Server.MapPath(".") + "/content.xml")
			Else
				doc.Load(Server.MapPath(".") + "/" + xmlFileName)
			End If

			pageRoot = doc.GetElementsByTagName("root")

			i = 0
			While i < pageRoot(0).ChildNodes.Count
				curNode = pageRoot(0).ChildNodes(i)
				If curNode.Attributes("id").Value = pageASPXFilename Then
					If curNode.HasChildNodes Then
						Dim k As Integer = 0
						Dim curNodeAttributes As XmlAttributeCollection
						k = 0
						While k < curNode.ChildNodes.Count
							curPageNode = curNode.ChildNodes(k)
							curNodeAttributes = curPageNode.Attributes
							Dim curControl As System.Web.UI.Control = Nothing
							If pageForm <> Nothing Then
								curControl = pageForm.FindControl(curNodeAttributes.GetNamedItem("item_id").Value)
							Else
								curControl = page.FindControl(curNodeAttributes.GetNamedItem("item_id").Value)
							End If

							If curControl <> Nothing Then
								Select Case curPageNode.Name
									Case "page_label"
										' init label text	
										Dim lbl As System.Web.UI.WebControls.Label = DirectCast((curControl), System.Web.UI.WebControls.Label)
										lbl.Text = curPageNode.InnerXml.Replace("[CUR_YEAR]", DateTime.Today.Year.ToString())
										Exit Select
									Case "page_link"
										' init hyperlink text
										Dim hl As System.Web.UI.WebControls.HyperLink = DirectCast((curControl), System.Web.UI.WebControls.HyperLink)
										hl.Text = curPageNode.InnerXml
										' init hyperlink href
										If curNodeAttributes.GetNamedItem("link") <> Nothing AndAlso curNodeAttributes.GetNamedItem("link").Value <> "" Then
											hl.NavigateUrl = curNodeAttributes.GetNamedItem("link").Value
										End If
										Exit Select
									Case "page_image"
										Dim img As System.Web.UI.WebControls.Image = DirectCast((curControl), System.Web.UI.WebControls.Image)
										img.ImageUrl = curNodeAttributes.GetNamedItem("src").Value
										img.AlternateText = curNodeAttributes.GetNamedItem("alt").Value
										img.Attributes.Add("title", curNodeAttributes.GetNamedItem("alt").Value)
										Exit Select
									Case "page_link_button"
										Dim lb As System.Web.UI.WebControls.LinkButton = DirectCast((curControl), System.Web.UI.WebControls.LinkButton)
										lb.Text = curPageNode.InnerXml
										Exit Select
									Case "page_image_button"
										Dim ib As System.Web.UI.WebControls.ImageButton = DirectCast((curControl), System.Web.UI.WebControls.ImageButton)
										ib.ImageUrl = curNodeAttributes.GetNamedItem("src").Value
										'ib.Text = curPageNode.InnerXml;
										Exit Select
									Case "page_button"
										Dim btn As System.Web.UI.WebControls.Button = DirectCast((curControl), System.Web.UI.WebControls.Button)
										btn.Text = HttpUtility.HtmlDecode(curPageNode.InnerXml)
										Exit Select
									Case "page_literal"
										Dim lit As System.Web.UI.WebControls.Literal = DirectCast((curControl), System.Web.UI.WebControls.Literal)
										lit.Text = curPageNode.InnerXml.Replace("[CUR_YEAR]", DateTime.Today.Year.ToString())
										Exit Select
									Case "page_textbox"
										Dim txt As System.Web.UI.WebControls.TextBox = DirectCast((curControl), System.Web.UI.WebControls.TextBox)
										txt.Text = curPageNode.InnerXml
										Exit Select
									Case "page_validator"
										Dim val As System.Web.UI.WebControls.BaseValidator = DirectCast((curControl), System.Web.UI.WebControls.BaseValidator)
										val.ErrorMessage = curPageNode.InnerXml
										Exit Select
									Case "page_checkbox"
										Dim chk As System.Web.UI.WebControls.CheckBox = DirectCast((curControl), System.Web.UI.WebControls.CheckBox)
										chk.Text = curPageNode.InnerXml
										Exit Select
								End Select
							Else
								'if ( curControl != null )
								Select Case curPageNode.Name
									Case "page_const"
										htPageConstants.Add(curNodeAttributes.GetNamedItem("item_id").Value, HttpUtility.HtmlDecode(curPageNode.InnerXml))
										Exit Select
								End Select
							End If
							System.Math.Max(System.Threading.Interlocked.Increment(k),k - 1)
						End While
					End If
					Exit While
				End If
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
		End Sub

		Public Sub initAdvertisements(ByVal pageForm As System.Web.UI.HtmlControls.HtmlForm, ByVal page As System.Web.UI.Page)
			Dim doc As New XmlDocument()
			Dim pageRoot As XmlNodeList = Nothing
			Dim curNode As XmlNode
			Dim curNodeAttributes As XmlAttributeCollection
			Dim i As Integer

			' TODO : validate xml
			doc.Load(Server.MapPath(".") + "/advertisements.xml")

			pageRoot = doc.GetElementsByTagName("root")

			i = 0
			While i < pageRoot(0).ChildNodes.Count
				curNode = pageRoot(0).ChildNodes(i)
				curNodeAttributes = curNode.Attributes
				Dim curControl As System.Web.UI.Control = Nothing
				If pageForm <> Nothing Then
					curControl = pageForm.FindControl(curNodeAttributes.GetNamedItem("item_id").Value)
				Else
					curControl = page.FindControl(curNodeAttributes.GetNamedItem("item_id").Value)
				End If

				If curControl <> Nothing Then
					Select Case curNode.Name
						Case "adv"
							' init label text	
							Dim lit As System.Web.UI.WebControls.Literal = DirectCast((curControl), System.Web.UI.WebControls.Literal)
							lit.Text = curNode.InnerXml
							Exit Select
					End Select
				End If
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While
		End Sub

		Public Function GetPageConstText(ByVal htPageConstants As Hashtable, ByVal sKey As String) As String
			Dim sReturn As String = ""
			If htPageConstants(sKey) <> Nothing Then
				sReturn = htPageConstants(sKey).ToString()
			End If

			Return sReturn
		End Function

		' Retrieve the logged-in user, by it's ID, stored in the sesion object
		Protected Function GetLoggedUser() As BO.User
			Dim usr As BO.User = Nothing

			Dim userID As Object = Session(Constants.ssnUserID)
			If userID <> Nothing Then
				usr = BO.Users.GetUserByID(DirectCast(userID, Integer))
			Else
				Dim userName As String = HttpContext.Current.User.Identity.Name
				If HttpContext.Current.User.Identity.IsAuthenticated Then
					Dim parts As String() = userName.Split(";"C)
					If parts.Length = 3 Then
						userID = Integer.Parse(parts(0))
						usr = BO.Users.GetUserByID(DirectCast(userID, Integer))
						Me.LoggedUser = usr
					End If
				End If
			End If

			Return usr
		End Function
	End Class
End Namespace






